//
//  TSJYViewController.m
//  Vpay
//
//  Created by 伟大大 on 2018/9/30.
//  Copyright © 2018年 丁伟佳. All rights reserved.
//

#import "TSJYViewController.h"

@interface TSJYViewController () {
    int height;
    
    NSMutableArray *myImageViewArray;
    
    NSMutableArray *ImageArray;

    float my_Height;

}
@property (nonatomic, strong) NSIndexPath *selectPath; //存放被点击的哪一行的标志

@end

@implementation TSJYViewController

#pragma mark -
#pragma mark - for lifeCircle
#pragma mark -
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"投诉建议";
    self.view = [[[NSBundle mainBundle]loadNibNamed:@"TSJYViewController" owner:self options:nil]lastObject];
    self.view.backgroundColor = BACKCOLOR;
    
    [self initData];
    [self initNavBtns];
    [self initViews];
    
    
        //增加监听，当键盘出现或改变时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
    
        //增加监听，当键退出时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    //    [NSThread detachNewThreadSelector:@selector(requestData) toTarget:self withObject:nil];
    
    //    [NSThread detachNewThreadSelector:@selector(requestDingdanData) toTarget:self withObject:nil];
}
#pragma mark -
#pragma mark - for datas
- (void)initData {
    self.array = [NSMutableArray arrayWithObjects:@"产品建议：用的不爽，我有建议",@"功能问题：功能故障或不可用",@"投诉：有问题来投诉，我们帮你做主",@"其他", nil];
    myImageViewArray = [[NSMutableArray alloc]init];
    ImageArray = [[NSMutableArray alloc]init];
}
#pragma mark -
#pragma mark -
#pragma mark - for Views
#pragma mark -

- (void)initNavBtns {
    
    self.navigationItem.leftBarButtonItem = [AppUtility getNavBtnItemLefBacktWith:@selector(leftNavBtnClicked) andTarget:self];
}
- (void)initViews {

    self.myTextView.delegate = self;
    
    self.Type_label.textColor = RGBCOLOR(34, 34, 34);
    
    self.myTableView.scrollEnabled = NO;
    self.myTableView.userInteractionEnabled = YES;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 30*theApp.autoSizeScaleY;
    self.myTableView.backgroundColor = BACKCOLOR;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction)];
    tap.delegate = self;
    tap.numberOfTouchesRequired = 1;
    [self.myTableView addGestureRecognizer:tap];
    
}
#pragma mark -
#pragma mark for evevts
#pragma mark -
- (void)leftNavBtnClicked {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)TapAction {
    
    if ([_myTextView isFirstResponder]) {
        [_myTextView resignFirstResponder];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    height = keyboardRect.size.height;
    
    self.myScrollView.contentSize = CGSizeMake(0, [AppUtility screenHeight]+height);
    
    UEXNSLog(@"%d",height);
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification{
    
    self.myScrollView.contentSize = CGSizeMake(0, [AppUtility screenHeight]+height);

    
}
#pragma mark -
#pragma mark for delegates
#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSMutableDictionary *dic = [self.array objectAtIndex:indexPath.row] ;
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell==nil) {
        //
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] ;
        
        {
            UILabel *banklabel = [[UILabel alloc]initWithFrame:CGRectMake(13*theApp.autoSizeScaleX, 9*theApp.autoSizeScaleY, 200*theApp.autoSizeScaleX, 10*theApp.autoSizeScaleY)];
            banklabel.textColor = RGBCOLOR(34, 34, 34);
            banklabel.tag = 10;
            banklabel.text = self.array[indexPath.row];
            banklabel.textAlignment = NSTextAlignmentLeft;
            
            banklabel.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:banklabel];
            
            
            
            UIView *spliteView = [[UIView alloc]initWithFrame:CGRectMake(0, 29*theApp.autoSizeScaleY , [AppUtility screenWidth], 1*theApp.autoSizeScaleY)];
            spliteView.backgroundColor = BACKCOLOR;
            
            [cell.contentView addSubview:spliteView];
            
        }
    }
    if (_selectPath == indexPath) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    int newRow = (int)[indexPath row];
    int oldRow = (int)(_selectPath != nil) ? (int)[_selectPath row]:-1;
    if (newRow != oldRow) {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
        UILabel *label = (UILabel *)[newCell.contentView viewWithTag:10];
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        label.textColor = RGBCOLOR(99, 171, 246);
        
        
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_selectPath];
        UILabel *label12 = (UILabel *)[oldCell.contentView viewWithTag:10];

        oldCell.accessoryType = UITableViewCellAccessoryNone;
        label12.textColor = RGBCOLOR(34, 34, 34);

        
        _selectPath = [indexPath copy];
        
        
        
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
- (void)textViewDidChange:(UITextView *)textView {
    SLog(@"length = %lu",(unsigned long)textView.text.length);
    self.Num_label.text = [NSString stringWithFormat:@"%lu/200",(unsigned long)textView.text.length];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        self.placeholder_label.hidden = NO;
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.placeholder_label.hidden = YES;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//    SLog(@"length = %lu",(unsigned long)textView.text.length);
    return YES;
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));

    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }else {
        [self.myTextView resignFirstResponder];
        return  YES;

    }
}

-(void)chooseImage {
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.allowsEditing = YES;
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"手机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册选择图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    
    [actionSheet addAction:cameraAction];
    [actionSheet addAction:photoAction];
    [actionSheet addAction:cancelAction];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}
//获取选择的图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
    
    
    for (UIImageView *iamgeview in myImageViewArray) {
        
        [iamgeview removeFromSuperview];
    }
    
    [myImageViewArray removeAllObjects];
    
    
//    UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
    [ImageArray addObject:image];
    
    
    float Height = self.Add_btn.frame.origin.y;
    int num =([ImageArray  count]%3==0)?(int)([ImageArray count]/3):((int)[ImageArray count]/3+1);
    
    
    for (int j = 0; j<num; j++) {
        
        if (j==[ImageArray count]/3)
        {
            for (int k = 0; k<[ImageArray count]%3; k++) {
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15+k*84, Height, 74, 74)];
                imageView.image =[ImageArray objectAtIndex:k+j*3];
                imageView.userInteractionEnabled = YES;
                [self.MidView addSubview:imageView];
                [myImageViewArray addObject:imageView];
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.tag = 1000 +j*3+k;
                [btn setFrame:CGRectMake1(45,45,15,15)];
                [btn setImage:[AppUtility getLocalImage:@"deletePH"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(ToDele:) forControlEvents:UIControlEventTouchUpInside];
                [imageView addSubview:btn];
                
            }
            
        }
        else
        {
            for (int k = 0; k<3; k++) {
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15+k*84, Height, 74, 74)];
                imageView.image =[ImageArray objectAtIndex:k+j*3];
                imageView.userInteractionEnabled = YES;
                [self.MidView addSubview:imageView];
                [myImageViewArray addObject:imageView];
                
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.tag = 1000 +j*3+k;
                [btn setFrame:CGRectMake1(45,45,15,15)];
                [btn setImage:[AppUtility getLocalImage:@"deletePH"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(ToDele:) forControlEvents:UIControlEventTouchUpInside];
                [imageView addSubview:btn];
            }
            
        }
        
        
//        Height = Height+60;
        
        
    }
    
    
    if ([ImageArray count]%3==0) {
        
//        Height=Height+60;
    }
    
    
    self.Add_btn.frame = CGRectMake(15+84*([ImageArray count]%3), Height, 74, 74);
    
//    middlebgView.frame = CGRectMake(middlebgView.frame.origin.x, Height+20, middlebgView.frame.size.width, middlebgView.frame.size.height);
    
//    self.myScrollView.contentSize = CGSizeMake([AppUtility screenWidth], Height+ middlebgView.frame.size.height+100);
    
    
    
//    [picker dismissModalViewControllerAnimated:YES];
    
    [self performSelector:@selector(selectPic:) withObject:image afterDelay:0.1];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
-(void)ToDele:(UIButton *)bbb
{
    
//    UIButton *tianjiabutton = (UIButton *)[self.view viewWithTag:999];
//    UIView *middlebgView = (UIView *)[self.view viewWithTag:10000];
//
    [ImageArray removeObjectAtIndex:bbb.tag-1000];
    
    for (UIImageView *iamgeview in myImageViewArray) {
        
        [iamgeview removeFromSuperview];
    }
    
    [myImageViewArray removeAllObjects];
    
    float Height =self.Add_btn.frame.origin.y;
    int num =([ImageArray  count]%3==0)?(int)([ImageArray count]/3):((int)[ImageArray count]/3+1);
    
    
    for (int j = 0; j<num; j++) {
        
        if (j==[ImageArray count]/3)
        {
            for (int k = 0; k<[ImageArray count]%3; k++) {
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15+k*84, Height, 74, 74)];
                imageView.image =[ImageArray objectAtIndex:k+j*3];
                imageView.userInteractionEnabled = YES;
                [self.MidView addSubview:imageView];
                [myImageViewArray addObject:imageView];
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.tag = 1000 +j*3+k;
                [btn setFrame:CGRectMake1(45,45,15,15)];
                [btn setImage:[AppUtility getLocalImage:@"deletePH"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(ToDele:) forControlEvents:UIControlEventTouchUpInside];
                [imageView addSubview:btn];
                
            }
            
        }
        else
        {
            for (int k = 0; k<3; k++) {
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15+k*84, Height, 74, 74)];
                imageView.image =[ImageArray objectAtIndex:k+j*3];
                imageView.userInteractionEnabled = YES;
                [self.MidView addSubview:imageView];
                [myImageViewArray addObject:imageView];
                
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.tag = 1000 +j*3+k;
                [btn setFrame:CGRectMake1(45,45,15,15)];
                [btn setImage:[AppUtility getLocalImage:@"deletePH"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(ToDele:) forControlEvents:UIControlEventTouchUpInside];
                [imageView addSubview:btn];
            }
            
        }
        
        
//        Height = Height+60;
        
        
    }
    
    
    if ([ImageArray count]%3==0) {
        
//        Height=Height+60;
    }
    
    
    self.Add_btn.frame = CGRectMake(15+84*([ImageArray count]%3), Height, 74, 74);
//
//    middlebgView.frame = CGRectMake(middlebgView.frame.origin.x, Height+20, middlebgView.frame.size.width, middlebgView.frame.size.height);
//
//    myScrollView.contentSize = CGSizeMake([AppUtility screenWidth], Height+ middlebgView.frame.size.height+100);
    
    
    
    
}
- (void)selectPic:(UIImage*)image
{
    
    //    NSMutableDictionary *resultDic = [NetUtility getDataWithURLStr:KURLheadpic andPostStr:nil andType:@"image/jpeg" andData:UIImageJPEGRepresentation(image,0.5) andDataKey:@"avatar"];
    //
    //
    //    UEXNSLog(@"avatar = %@",resultDic);
    //    if ([resultDic[@"status"] intValue] == 0) {
    //        [self.view makeToast:resultDic[@"info"]];
    //
    //    }
    //    else {
    //        [self.view makeToast:@"头像修改成功"];
    //    }
    
    //    [NSThread detachNewThreadSelector:@selector(RequestUserInfoData) toTarget:self withObject:nil];
    //    [self.Person_imageView setImage:image];
    
    
    return;
}
//从相机或者相册界面弹出
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    [_myScrollView release];
    [_myTableView release];
    [_myTextView release];
    [_Num_label release];
    [_placeholder_label release];
    [_Type_label release];
    [_MidView release];
    [_Add_btn release];
    [super dealloc];
}

- (IBAction)TJ_btnClik:(UIButton *)sender {
    SLog(@"4444");
    
    NSString *postStr = [NSString stringWithFormat:@"userid=%@&content=%@",@"",_myTextView.text];
    
    
    NSDictionary *resultDict = [NetUtility getDataWithURLStr:KURLTsJy andPostStr:postStr];
    
    //    NSDictionary *resultDict =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@%@",KURLRegister,postStr] andPostStr:nil andView:self.navigationController.view];
    
    
    UEXNSLog(@"URL---==%@%@ kURLRegister dict=%@",KURLTsJy,postStr,resultDict);
    
    
    if (resultDict) {
        int status = [[resultDict objectForKey:@"s"] intValue];
        
        
        if (status==1) {
            
            [self.navigationController.view makeToast:[resultDict objectForKey:@"i"]];
            
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }else {
            [self.navigationController.view makeToast:[resultDict objectForKey:@"i"]];
            
        }
    }
    
}
- (IBAction)Add_btnClik:(UIButton *)sender {
    
    [self chooseImage];
}
@end
